#实现一个命令行版本的学生管理系统
import sys
import os
students = []
def save():
    """
    存档函数
    """
    with open('record.txt','w',encoding='utf-8') as f:
        for s in students:
            f.write(f'{s['studentId']}\t{s['name']}\t{s['gender']}\t{s['classId']}\n')
    print(f'存档成功，共存储了{len(students)}条记录')

def load():
    """
    读档函数
    """
#     若读档文件不存在直接跳过
    if not os.path.exists('record.txt'):
        return
    # 读取文档，先清空旧的数据
    global students
    students = []
    with open('record.txt','r',encoding='utf-8') as f:
        for line in f:
#        按\t切分
#         切分前要取出行首与行末的空百符号
            line = line.strip()
            tokens = line.split('\t')
            if len(tokens) != 4:
                print(f'当前行{line}存在问题')
                continue
            student = {
                'studentId': tokens[0],
                'name': tokens[1],
                'gender': tokens[2],
                'classId': tokens[3],
            }
            students.append(student)
    print(f'读档成功，共读取了{len(students)}条记录')


def menu():
    print(' 1.增加学生')
    print(' 2.显示学生')
    print(' 3.查找学生')
    print(' 4.删除学生')
    print(' 0.退出程序')
    choice = input('请输入你的选择：')
    return choice

def insert():
    print('-------------------------------------------')
    print('                [新增学生]...')
    global students
    name = input('请输入新增学生姓名：')
    studentId = input('请输入新增学生学号：')
    for s in students:
        if s['studentId'] == studentId:
            print(f'{s["studentId"]}学生已存在')
            print('------------------------------------')
            return
    gender = input('请输入新增学生性别：')
    if gender not in ('男','女'):
        print('性别输入不合法，新增错误！！！')
        return
    classId = input('请输入新增学生班级：')
    student = {
        'name': name,
        'studentId': studentId,
        'gender': gender,
        'classId': classId
    }
    students.append(student)
    save()
    print('                [新增学生]over')
    print('-------------------------------------------')


def show():
    print('-------------------------------------------')
    print('             [显示学生信息]...')
    for s in students:
        print(f"[{s['studentId']}]\t{s['name']}\t{s['gender']}\t{s['classId']}")
    print(f"  [显示学生信息]over，共有[{len(students)}]个学生")
    print('-------------------------------------------')

def find():
    print('-------------------------------------------')
    print('             [查找学生]...')
    name = input('请输入要查找的学生姓名：')
    count = 0
    for s in students:
        if s['name'] == name:
            print(f"[{s['studentId']}]\t{s['name']}\t{s['gender']}")
            count += 1
    if count == 0:
        print('查无此人！！！')
    else:
        print(f'共有[{count}]个匹配学生')
    print('             [查找学生]over')
    print('-------------------------------------------')

def delete():
    print('-------------------------------------------')
    print('             [删除学生]...')
    studentId = input('请输入要删除学生的学号：')
    flag =  True
    for s in students:
        if s['studentId'] == studentId:
            students.remove(s)
            print('[删除该学生成功]')
            flag = False
    if flag:
        print(f'{studentId}该学生不存在')
    save()
    print('             [删除学生]over')
    print('-------------------------------------------')

def main():
    """
    入口函数
    """
    print('----------------------------')
    print('     欢迎来到学生管理系统     ')
    print('----------------------------')
    load()
    while True:
        choice = menu()
        if choice == '1':
            insert()
        elif choice == '2':
            show()
        elif choice == '3':
            find()
        elif choice == '4':
            delete()
        elif choice == '0':
            print('goodbye!')
            sys.exit(0)
        else:
            print('输入不合法，请重新输入')

main()
